// pages/login/login.js
//获取应用实例
const app = getApp()
const util = require('../../../utils/util.js')
let NFCAdapter = null ;
Page({
  /**
   * 页面的初始数据
   */
  data: {
    loadding : 0,   
    isJump: undefined,
    isDiscovery: undefined,
    isInit:true,
    isFlag:0,
    dutyWeekBea: [],
        selectedIndex: -1,
        currentMacaddress: "",
        currentcheckAddress: "",
        currentcheckPointId: "",
        categoryid:"",
        category:"",
        zhizhouErr:0,

  },
  onLoad: function(options) {
    console.log("nfc感应区")
    if(options.inspectPlanId == undefined){
      this.setData({
        isFlag : 4
      })
    }else{
      this.setData({
        isFlag : 2,
        inspectPlanId:options.inspectPlanId
      })
    }
    // this.initNFC()
  },
  onShow:function(){
    this.setData({
      isJump: true ,
      isDiscovery : true,
      isInit:true 
    })
    this.initNFC()
  },
  onUnload:function(){
    console.log("onUnload NFC")
    this.closeNFC() ;
  },

  //NFC测试
  initNFC:function(){
    NFCAdapter = wx.getNFCAdapter() ;
    console.log("NFCAdapter实例1",NFCAdapter)
    console.log("isInit",this.data.isInit)
    if(this.data.isInit){
      NFCAdapter.startDiscovery({
        success: res => {
          console.log("请将设备放入识别区NFC",res)
        },
        fail: error => {
          console.error(error);
        },
        complete: res => {
          this.setData({
            isInit:false 
          })
        }
      });
    }
    NFCAdapter.onDiscovered(callback => {
      if(this.data.isDiscovery){
        this.setData({
          isDiscovery:false
        })
        //设备放入识别区后，监听回调返回的对象callback 中处理获取到的标签内容,主要是获取NFC卡中的唯一标志aid
        let aid = parseInt(this.ab2hex(callback.id), 16);
        console.log("success, aid : ", aid)
        //根据NFC设备号查看数据库是否有，如果没有则绑定添加。
        wx.request({
          url: app.inspectUrl + '/WeChat/weChatSystem/isNFCDeviceId',
          method: 'POST',
          dataType: 'json',
          data: {
            schoolId : parseInt(app.globalData.departmentId) ,
            macAddress : aid
          },
          success: res => {
      console.log(aid, res.data);
    //   wx.request({
    //     url: app.baseUrl +'/WeChat/weChatSystem/getZhizhoucontentByMacaddress',
    //     method: 'GET',
    //     dataType:'json',
    //     data:{
    //       macAddress: aid
    //     },
    //     success: res =>{
    // //       if(res.data.type==3){
    // //         this.setData({
    // //           currentMacaddress: res.data.macAddress,
    // //           currentcheckAddress: res.data.address,
    // //           currentcheckPointId: res.data.id,
    // //           categoryid:res.data.categoryId,
    // //           category:res.data.category,
    // //         })
    // //         let that = this
    // // if (that.data.currentMacaddress != "" && that.data.currentcheckAddress != "" && that.data.currentcheckPointId != "") {
    // //   wx.navigateTo({
        
    // //     url: `/pages/dutyweekItemList/dutyweekItemList?currentMacaddress=${that.data.currentMacaddress}&currentcheckAddress=${that.data.currentcheckAddress}&currentcategoryid=${that.data.categoryid}&currentcheckPointId=${that.data.currentcheckPointId}&currentcategory=${that.data.category}`
    // //   })
    // //   console.log("===", that.data);
    // //   this.setData({
    // //     dutyWeekBea: [],
    // //     selectedIndex: -1,
    // //     currentMacaddress: "",
    // //     currentcheckAddress: "",
    // //     currentcheckPointId: "",
    // //   })
    // // }
    // //       }
    //     }
    //   })
            this.toOtherNFCPage(aid,res.data)
          }
        })
      }
    });
  },

  //数据转换得方法 NFC
 byteToString :function(arr) {
	if (typeof arr === 'string') {
		return arr;
	}
	var str = '',
		_arr = arr;
	for (var i = 0; i < _arr.length; i++) {
		var one = _arr[i].toString(2),
			v = one.match(/^1+?(?=0)/);
		if (v && one.length == 8) {
			var bytesLength = v[0].length;
			var store = _arr[i].toString(2).slice(7 - bytesLength);
			for (var st = 1; st < bytesLength; st++) {
				store += _arr[st + i].toString(2).slice(2);
			}
			str += String.fromCharCode(parseInt(store, 2));
			i += bytesLength - 1;
		} else {
			str += String.fromCharCode(_arr[i]);
		}
	}
	return str;
 },
  /**
   * 格式化得到aid值 NFC
   * @param {Object} buffer
   */
  ab2hex:function(buffer) {
    var hexArr = Array.prototype.map.call(
      new Uint8Array(buffer),
      function(bit) {
        return ('00' + bit.toString(16)).slice(-2);
      }
    );
    return hexArr.join('');
  },
  //退出当前页或者退出小程序再把对象都清理一下
  closeNFC:function(){
    NFCAdapter.offDiscovered(callback => {})
    NFCAdapter.stopDiscovery();
    console.log("关闭监听")
    this.setData({
      isJump : false ,
      isDiscovery: false
    })
  }, 

  //感应到nfc标签就跳转到绑定界面或者设备详情界面
  toOtherNFCPage:function(aid,flag){
      // wx.request({
      //   url: app.baseUrl + '/weChatSystem/isNFCDeviceId',
      //   method: 'POST',
      //   dataType: 'json',
      //   data: {
      //     schoolId : parseInt(app.globalData.departmentId) ,
      //     macAddress : '23539726212503620'
      //   },
      //   success: res => {
      //     console.log(res)
      //     if(res.data == 'success'){
      //       console.log("success，nfc巡检")
      //       wx.navigateTo({
      //         url: `/subpages/pages/nfcInspect/nfcInspect?aid=23539726212503620`,
      //       })
      //     }else{
      //       //nfc绑定
      //       console.log("fail，nfc绑定")
      //       wx.navigateTo({
      //         url: `/subpages/pages/nfcBinding/nfcBinding?aid=23539726212503620`,
      //       })
      //     }
      //   }
      // })
      if(this.data.isJump){
        if(flag == 'success'){
        //   wx.request({
        //     url: app.baseUrl +'/WeChat/weChatSystem/getNFCcheckpointType',
        //     method: 'GET',
        // dataType:'json',
        // data:{
        //   macAddress: aid
        // },
        // success: res1=>{
        //   if(res1.data.type==3){
        //     wx.request({
        //       url: app.baseUrl +'/WeChat/weChatSystem/getZhizhoucontentByMacaddress',
        //       method: 'GET',
        //       dataType:'json',
        //       data:{
        //         macAddress: aid
        //       },
        //       success: res =>{
        //         console.log("值周",res.data)
        //          if(res.data.length == 0){
        //           this.setData({
        //             zhizhouErr:1
        //           })
        //          }else{
        //           this.setData({
        //             zhizhouErr:0
        //           })
        //          }
        //          console.log("ERR",this.data.zhizhouErr)
        //         if(res1.data.type==3){
        //           this.setData({
        //             currentMacaddress: res.data.macAddress,
        //             currentcheckAddress: res.data.address,
        //             currentcheckPointId: res.data.id,
        //             categoryid:res.data.categoryId,
        //             category:res.data.category,
        //           })
        //           let that = this
        //   if (that.data.currentMacaddress != "" && that.data.currentcheckAddress != "" && that.data.currentcheckPointId != "") {
        //     wx.navigateTo({
              
        //       url: `/pages/dutyweekItemList/dutyweekItemList?currentMacaddress=${that.data.currentMacaddress}&currentcheckAddress=${that.data.currentcheckAddress}&currentcategoryid=${that.data.categoryid}&currentcheckPointId=${that.data.currentcheckPointId}&currentcategory=${that.data.category}&zhizhouErr=${that.data.zhizhouErr}`
        //     })
        //     console.log("===", that.data);
        //     this.setData({
        //       dutyWeekBea: [],
        //       selectedIndex: -1,
        //       currentMacaddress: "",
        //       currentcheckAddress: "",
        //       currentcheckPointId: "",
        //     })
        //   }
        //         }
        //       }
        //     })
        //   }
        //   else if(res.data.type==2){
        //     console.log("success，nfc巡检")
        //     wx.navigateTo({
        //       url: `/subpages/pages/nfcInspect/nfcInspect?aid=`+aid,
        //     })
        //   }
        // }
        //   })
        wx.showToast({
          title: '此卡已绑定！',
          image: "../../../images/error.png"
        })
         
        }else{
          //nfc绑定
          console.log("fail，nfc绑定")
          wx.navigateTo({
            url: `/subpages/pages/nfcBinding/nfcBinding?aid=`+aid,
          })
        }
        this.setData({
          isJump : false
        })
        this.closeNFC()
      }
  },
  
  nfcaddressCondition:function(e){
    wx.navigateTo({
      url: '/subpages/pages/cancelNFCBind/cancelNFCBind'
    
    })
  }
  
})

